;(function () {
    'use strict';
    var $form_add_task = $('.add-task')
        , $task_delete_trigger
        , $task_detail_trigger
        , $task_detail = $('.task-detail')
        , $task_detail_mask = $('.task-detail-mask')
        , $task_detail_content
        , $checkbox_complete
        , $task_detail_input_content
        , task_list = []
        , current_index
        , $msg = $('.msg')
        , $msg_content = $msg.find('.msg-content')
        , $msg_confirm = $msg.find('.confirmed')
        , $alerter = $('.alerter')
        , $update_form;

    init();
    
    $form_add_task.on('submit', on_add_task_form_submit);

    $task_detail_mask.on('click', hide_task_detail);



    function listen_msg_event() {
        $msg_confirm.on('click', function () {
            hide_msg();
        })
    }


    function on_add_task_form_submit(e) {

        var new_task = {};
        /*禁用默认行为, 不让表单提交*/
        e.preventDefault();
        /*获取新Task的值*/
        var $input = $(this).find('input[type=text]');
        new_task.content = $input.val();
        /*如果新Task的值为空 则直接返回*/
        if (!new_task.content) return;
        /*存入新的Task*/
        if (add_task(new_task)) {
            $input.val(null);
        }

    }

    function listen_task_detail() {
        var index;
        $('.task-item').on('dblclick', function () {
            index = $(this).data('index');
            show_task_detail(index);

        });
        $task_detail_trigger.on('click', function () {
            var $this = $(this);
            var $item = $this.parent().parent();
            index =  $item.data('index');
            show_task_detail(index);
        })
    }

    /*查找并监听所有删除按钮的点击事件*/
    function listen_task_delete() {
        $task_delete_trigger.on('click', function () {
            var $this = $(this);
            var $item = $this.parent().parent();
            var index =  $item.data('index');
            /*确认删除*/
            var tmp = confirm('确定删除？');
            tmp ? delete_task(index) : null;
        });
    }


    /*监听完成任务事件*/
    function listen_checkbox_complete() {
        $checkbox_complete.on('click', function () {
            var $this = $(this);
            var index = $this.parent().parent().data('index');
            var item  = get(index);
            if (item && item.complete) {
                update_task(index, {complete: false});
            } else {
                update_task(index, {complete: true});
            }

        })
    }
    


    function get(index) {
        return store.get('task_list')[index];
    }

    /*查看Task详情*/
    function show_task_detail(index) {

        /*生成详情模板*/
        render_task_detail(index);
        current_index = index;
        /*显示详情模板，默认隐藏*/
        $task_detail.show();
        $task_detail_mask.show();
    }

    /*更新Task*/
    function update_task(index, data) {

        if (!index || !task_list[index]) return;

        task_list[index] = $.extend({}, task_list[index], data);
        refresh_task_list();
    }

    function hide_task_detail() {
        $task_detail.hide();
        $task_detail_mask.hide();

    }

    /*渲染指定Task指定信息*/
    function render_task_detail(index) {

        if (index === undefined || !task_list[index]) return;

        var item = task_list[index];

        var tpl = '<form>'+
                        '<div class="content">'+ item.content +'</div><!--任务标题-->'+
                        '<div class="input-item"><input type="text" style="display: none;" name="content" value="'+ (item.content || '') +'"></div><!--任务标text题-->'+
                        '<div>'+
                            '<div class="desc input-item"><!--任务描述-->'+
                                '<textarea name="desc">'+ (item.desc || '') +'</textarea>'+
                            '</div>'+
                         '</div>'+
                        '<div class="remind input-item">'+
                                '<label>提醒时间</label>'+
                                '<input class="datetime" name="remind_date" type="text" value="'+(item.remind_date || '') +'" autocomplete="off">'+
                            '<!--<button type="submit">submit</button>-->'+
                        '</div>'+
                        '<div class="input-item"><button type="submit">更新</button></div>'+
                 '</form>';

        /*清空Task详情模板, 再设置新模板*/
        $task_detail.html('');
        $task_detail.html(tpl);
        $('.datetime').datetimepicker();
        /*选中其中的form元素，之后会使用其监听submit事件*/
        $update_form = $task_detail.find('form');
        /*选中显示Task内容的元素*/
        $task_detail_content = $update_form.find('.content');
        /*选中显示Task input的元素*/
        $task_detail_input_content = $update_form.find('[name=content]');

        /*双击内容元素会显示input, 隐藏自己*/
        $task_detail_content.on('dblclick', function () {
            $task_detail_content.hide();
            $task_detail_input_content.show();
        });

        $update_form.on('submit', function (e) {
            /*禁用默认行为, 不让表单提交*/
            e.preventDefault();
            var data = {};
            /*获取表单中的值*/
            data.content = $(this).find('[name=content]').val();
            data.desc = $(this).find('[name=desc]').val();
            data.remind_date = $(this).find('[name=remind_date]').val();
            /*更新Task*/
            update_task(index, data);
            /*隐藏编辑页面*/
            hide_task_detail();
        })
    }

    function add_task(new_task) {
        /*将新Task推入task_list*/
        task_list.push(new_task);
        /*更新localStorage*/
        refresh_task_list();

        return true;
    }

    /*刷新localStorage数据并渲染模板*/
    function refresh_task_list() {

        store.set('task_list', task_list);
        render_task_list();
    }

    /*删除一条Task*/
    function delete_task(index) {
        console.log("index", index);
        /*如果没有index，或者index不存在*/
        if (index === undefined || !task_list[index]) return;

        delete task_list[index];
        /*更新localStorage*/
        refresh_task_list();
    }
    
    function init() {
        task_list = store.get('task_list') || [];
        if (task_list.length) {
            refresh_task_list()
        }

        task_remind_check();

        listen_msg_event();
    }

    function task_remind_check() {
        var current_timestamp;
        var itl = setInterval(function () {
            for (var i = 0; i < task_list.length; i++) {
                var item = get(i), task_timestamp;
                if (!item || !item.remind_date || item.informed) continue;

                current_timestamp = (new Date()).getTime();
                task_timestamp = (new Date(item.remind_date)).getTime();
                if (current_timestamp - task_timestamp >= 1) {
                    update_task(i, {informed: true})
                    show_msg(item.content);
                }
            }
        }, 300);
    }

    function show_msg(msg) {
        if (!msg) return;
        $alerter.get(0).play();
        $msg_content.html(msg);
        $msg.show();
    }

    function hide_msg() {
        $alerter.get(0).pause();
        $msg.hide();
    }

    /*渲染全部的Task模板*/
    function render_task_list() {
        var $task_list = $('.task-list');
        $task_list.html('');
        var complete_items = [];
        for(var i = 0; i < task_list.length; i++) {
            var item = task_list[i];
            if (item && item.complete) {
                complete_items[i] = item;
            } else {
                var $task = render_task_item(item, i);
                $task_list.prepend($task);
            }

        }

        for (var i = 0; i < complete_items.length; i++) {

            var item = (complete_items[i]);
            var $task = render_task_item(item, i);
            if (!$task) continue;

            $task.addClass('completed');
            $task_list.append($task);
        }

        /*设置监听*/
        $task_delete_trigger = $('.action.delete');//.action.delete 同个class的写法
        $task_detail_trigger = $('.action.detail');
        $checkbox_complete = $('.task-item .complete[type=checkbox]');//.task-item .complete 不同个class的写法
        listen_task_delete();
        listen_task_detail();
        listen_checkbox_complete();

    }

    /*渲染单条Task模板*/
    function render_task_item(data, index) {

        if (!data || !index) return;

        var list_item_tpl = '<div class="task-item" data-index='+ index +'>' +
            '                <span><input class="complete" '+ (data.complete ? 'checked': '') +' type="checkbox" ></span>' +
            '                <span class="task-content">' + data.content + '</span>' +
                            '<span class="fr">'+
            '                   <span>' + (data.remind_date || '') + '</span>' +
            '                   <span class="action delete">删除</span>' +
            '                   <span class="action detail">详细</span>' +
                            '</span>'+
            '            </div>';

        return $(list_item_tpl);
    }
})();